// 全局状态管理器
// 协调各个模块的状态，提供跨模块数据共享机制

import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { persist } from 'zustand/middleware';
import { ViewType } from '../types/router';

// 应用主题类型
export type AppTheme = 'light' | 'dark' | 'system';

// 应用语言类型
export type AppLanguage = 'zh-CN' | 'en-US';

// 全局设置接口
export interface GlobalSettings {
  theme: AppTheme;
  language: AppLanguage;
  autoSave: boolean;
  autoSaveInterval: number; // 秒
  sessionRecovery: boolean;
  fontSize: number;
  tabSize: number;
  wordWrap: boolean;
  lineNumbers: boolean;
  editorTheme: string;
  compactMode: boolean;
  maxTabs: number;
  lazyLoading: boolean;
  performanceMonitor: boolean;
  developerMode: boolean;
  experimentalFeatures: boolean;
}

// 应用状态接口
export interface AppState {
  isInitialized: boolean;
  isLoading: boolean;
  error: string | null;
  currentWorkspace: string | null;
  recentWorkspaces: string[];
  windowState: {
    isMaximized: boolean;
    isFullscreen: boolean;
    bounds: {
      x: number;
      y: number;
      width: number;
      height: number;
    };
  };
}

// 模块状态接口
export interface ModuleStates {
  editor: {
    activeTabId: string | null;
    tabCount: number;
    hasUnsavedChanges: boolean;
  };
  dashboard: {
    lastAnalyzed: string | null;
    projectStats: any | null;
  };
  graph: {
    selectedNodeId: string | null;
    viewMode: 'overview' | 'detailed';
    graphData: any | null;
  };
  settings: {
    activeSection: string;
    hasUnsavedSettings: boolean;
  };
}

// 通知接口
export interface Notification {
  id: string;
  type: 'info' | 'success' | 'warning' | 'error';
  title: string;
  message: string;
  timestamp: number;
  duration?: number; // 自动关闭时间，0表示不自动关闭
  actions?: Array<{
    label: string;
    action: () => void;
  }>;
}

// 全局状态接口
export interface GlobalState {
  // 基础状态
  app: AppState;
  settings: GlobalSettings;
  modules: ModuleStates;
  
  // UI状态
  notifications: Notification[];
  sidebarCollapsed: boolean;
  panelCollapsed: boolean;
  
  // 性能监控
  performance: {
    memoryUsage: number;
    cpuUsage: number;
    renderTime: number;
    lastUpdate: number;
  };
}

// 全局操作接口
export interface GlobalActions {
  // 应用操作
  initialize: () => Promise<void>;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  clearError: () => void;
  
  // 工作区操作
  setCurrentWorkspace: (workspace: string | null) => void;
  addRecentWorkspace: (workspace: string) => void;
  removeRecentWorkspace: (workspace: string) => void;
  
  // 设置操作
  updateSetting: <K extends keyof GlobalSettings>(key: K, value: GlobalSettings[K]) => void;
  resetSettings: () => void;
  importSettings: (settings: Partial<GlobalSettings>) => void;
  exportSettings: () => GlobalSettings;
  
  // 模块状态操作
  updateModuleState: <K extends keyof ModuleStates>(
    module: K, 
    state: Partial<ModuleStates[K]>
  ) => void;
  
  // 通知操作
  addNotification: (notification: Omit<Notification, 'id' | 'timestamp'>) => string;
  removeNotification: (id: string) => void;
  clearNotifications: () => void;
  
  // UI操作
  toggleSidebar: () => void;
  togglePanel: () => void;
  setSidebarCollapsed: (collapsed: boolean) => void;
  setPanelCollapsed: (collapsed: boolean) => void;
  
  // 窗口操作
  updateWindowState: (state: Partial<AppState['windowState']>) => void;
  
  // 性能监控
  updatePerformanceMetrics: (metrics: Partial<GlobalState['performance']>) => void;
}

// 默认设置
const defaultSettings: GlobalSettings = {
  theme: 'system',
  language: 'zh-CN',
  autoSave: true,
  autoSaveInterval: 30,
  sessionRecovery: true,
  fontSize: 14,
  tabSize: 2,
  wordWrap: true,
  lineNumbers: true,
  editorTheme: 'vs-dark',
  compactMode: false,
  maxTabs: 20,
  lazyLoading: true,
  performanceMonitor: false,
  developerMode: false,
  experimentalFeatures: false,
};

// 默认应用状态
const defaultAppState: AppState = {
  isInitialized: false,
  isLoading: false,
  error: null,
  currentWorkspace: null,
  recentWorkspaces: [],
  windowState: {
    isMaximized: false,
    isFullscreen: false,
    bounds: {
      x: 100,
      y: 100,
      width: 1200,
      height: 800,
    },
  },
};

// 默认模块状态
const defaultModuleStates: ModuleStates = {
  editor: {
    activeTabId: null,
    tabCount: 0,
    hasUnsavedChanges: false,
  },
  dashboard: {
    lastAnalyzed: null,
    projectStats: null,
  },
  graph: {
    selectedNodeId: null,
    viewMode: 'overview',
    graphData: null,
  },
  settings: {
    activeSection: 'general',
    hasUnsavedSettings: false,
  },
};

// 全局Store类型
export type GlobalStore = GlobalState & GlobalActions;

// 创建全局Store
export const useGlobalStore = create<GlobalStore>()(
  subscribeWithSelector(
    persist(
      (set, get) => ({
        // 初始状态
        app: { ...defaultAppState },
        settings: { ...defaultSettings },
        modules: { ...defaultModuleStates },
        notifications: [],
        sidebarCollapsed: false,
        panelCollapsed: false,
        performance: {
          memoryUsage: 0,
          cpuUsage: 0,
          renderTime: 0,
          lastUpdate: Date.now(),
        },

        // 应用操作
        initialize: async () => {
          set(state => ({
            app: {
              ...state.app,
              isLoading: true,
              error: null,
            }
          }));

          try {
            // 这里可以添加初始化逻辑
            // 比如加载用户设置、恢复会话等
            
            await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟初始化

            set(state => ({
              app: {
                ...state.app,
                isInitialized: true,
                isLoading: false,
              }
            }));
          } catch (error) {
            set(state => ({
              app: {
                ...state.app,
                isLoading: false,
                error: error instanceof Error ? error.message : 'Initialization failed',
              }
            }));
          }
        },

        setLoading: (loading: boolean) => {
          set(state => ({
            app: {
              ...state.app,
              isLoading: loading,
            }
          }));
        },

        setError: (error: string | null) => {
          set(state => ({
            app: {
              ...state.app,
              error,
            }
          }));
        },

        clearError: () => {
          set(state => ({
            app: {
              ...state.app,
              error: null,
            }
          }));
        },

        // 工作区操作
        setCurrentWorkspace: (workspace: string | null) => {
          set(state => ({
            app: {
              ...state.app,
              currentWorkspace: workspace,
            }
          }));
        },

        addRecentWorkspace: (workspace: string) => {
          set(state => {
            const recentWorkspaces = [
              workspace,
              ...state.app.recentWorkspaces.filter(w => w !== workspace)
            ].slice(0, 10); // 最多保留10个最近工作区

            return {
              app: {
                ...state.app,
                recentWorkspaces,
              }
            };
          });
        },

        removeRecentWorkspace: (workspace: string) => {
          set(state => ({
            app: {
              ...state.app,
              recentWorkspaces: state.app.recentWorkspaces.filter(w => w !== workspace),
            }
          }));
        },

        // 设置操作
        updateSetting: (key, value) => {
          set(state => ({
            settings: {
              ...state.settings,
              [key]: value,
            }
          }));
        },

        resetSettings: () => {
          set(state => ({
            settings: { ...defaultSettings }
          }));
        },

        importSettings: (settings) => {
          set(state => ({
            settings: {
              ...state.settings,
              ...settings,
            }
          }));
        },

        exportSettings: () => {
          return get().settings;
        },

        // 模块状态操作
        updateModuleState: (module, moduleState) => {
          set(state => ({
            modules: {
              ...state.modules,
              [module]: {
                ...state.modules[module],
                ...moduleState,
              }
            }
          }));
        },

        // 通知操作
        addNotification: (notification) => {
          const id = `notification_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
          const newNotification: Notification = {
            ...notification,
            id,
            timestamp: Date.now(),
          };

          set(state => ({
            notifications: [...state.notifications, newNotification]
          }));

          // 自动移除通知
          if (notification.duration && notification.duration > 0) {
            setTimeout(() => {
              get().removeNotification(id);
            }, notification.duration);
          }

          return id;
        },

        removeNotification: (id) => {
          set(state => ({
            notifications: state.notifications.filter(n => n.id !== id)
          }));
        },

        clearNotifications: () => {
          set({ notifications: [] });
        },

        // UI操作
        toggleSidebar: () => {
          set(state => ({
            sidebarCollapsed: !state.sidebarCollapsed
          }));
        },

        togglePanel: () => {
          set(state => ({
            panelCollapsed: !state.panelCollapsed
          }));
        },

        setSidebarCollapsed: (collapsed) => {
          set({ sidebarCollapsed: collapsed });
        },

        setPanelCollapsed: (collapsed) => {
          set({ panelCollapsed: collapsed });
        },

        // 窗口操作
        updateWindowState: (windowState) => {
          set(state => ({
            app: {
              ...state.app,
              windowState: {
                ...state.app.windowState,
                ...windowState,
              }
            }
          }));
        },

        // 性能监控
        updatePerformanceMetrics: (metrics) => {
          set(state => ({
            performance: {
              ...state.performance,
              ...metrics,
              lastUpdate: Date.now(),
            }
          }));
        },
      }),
      {
        name: 'global-store',
        partialize: (state) => ({
          settings: state.settings,
          app: {
            currentWorkspace: state.app.currentWorkspace,
            recentWorkspaces: state.app.recentWorkspaces,
            windowState: state.app.windowState,
          },
          sidebarCollapsed: state.sidebarCollapsed,
          panelCollapsed: state.panelCollapsed,
        }),
      }
    )
  )
);

// 选择器hooks
export const useAppState = () => useGlobalStore(state => state.app);
export const useSettings = () => useGlobalStore(state => state.settings);
export const useModuleStates = () => useGlobalStore(state => state.modules);
export const useNotifications = () => useGlobalStore(state => state.notifications);
export const usePerformanceMetrics = () => useGlobalStore(state => state.performance);

// 操作hooks
export const useGlobalActions = () => {
  const store = useGlobalStore();
  return {
    initialize: store.initialize,
    setLoading: store.setLoading,
    setError: store.setError,
    clearError: store.clearError,
    setCurrentWorkspace: store.setCurrentWorkspace,
    addRecentWorkspace: store.addRecentWorkspace,
    removeRecentWorkspace: store.removeRecentWorkspace,
    updateSetting: store.updateSetting,
    resetSettings: store.resetSettings,
    importSettings: store.importSettings,
    exportSettings: store.exportSettings,
    updateModuleState: store.updateModuleState,
    addNotification: store.addNotification,
    removeNotification: store.removeNotification,
    clearNotifications: store.clearNotifications,
    toggleSidebar: store.toggleSidebar,
    togglePanel: store.togglePanel,
    setSidebarCollapsed: store.setSidebarCollapsed,
    setPanelCollapsed: store.setPanelCollapsed,
    updateWindowState: store.updateWindowState,
    updatePerformanceMetrics: store.updatePerformanceMetrics,
  };
};
